/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package teacher;

import common.*;
import java.io.BufferedOutputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

/**
 * Tcp套接字消息发送线程
 *
 * @author Eugene-Forest
 */
public class NoticeThread extends Thread {

    private MessageModel messageModel = null;
    private Socket s = null;

    public NoticeThread(MessageModel messageModel) {
        this.messageModel = messageModel;
    }

    public NoticeThread(Socket socket, MessageModel messageModel) {
        this.messageModel = messageModel;
        this.s = socket;
    }

    public NoticeThread(Socket s) {
        this.s = s;
    }

    @Override
    public void run() {
        try {
            //判断是否是定向发送公告历史
            int number=0;
            if (s == null) {
                //未指定套接字说明不是定向发送公告历史而是群发公告
                for (Socket socket : DataCenter.get_sockets()) {
                    number++;
                    System.out.println("【"+number+"】"+socket.toString()+" had sended a real time notice");
                    //没有判断套接字是否关闭，可能会出错
                    ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(socket.getOutputStream()));
                    oos.writeObject(messageModel);
                    oos.flush();
                }
            } else {
                //指定了套接字，判断是否还指定了发送的信息对象
                if (messageModel == null) {
                    //未指定发送的信息对象，说明此次公告任务是定向发送公告历史
                    for (MessageModel mm : DataCenter.get_messageModels()) {
                        ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(s.getOutputStream()));
                        oos.writeObject(mm);
                        oos.flush();
                    }
                } else {
                    //指定了发送的信息对象,说明是一次定向公告
                    ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(s.getOutputStream()));
                    oos.writeObject(messageModel);
                    oos.flush();
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
